package com.lqzs.businessmanager.http

import android.util.Log
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okio.Buffer
import java.io.EOFException
import java.io.IOException
import java.nio.charset.Charset
import java.util.Locale

class LogInterceptor : Interceptor {

    companion object{
        val TAG: String = javaClass.name
    }


    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request: Request = chain.request()
        //the request url
        val url = request.url.toString()
        //the request method
        val method = request.method
        val t1 = System.nanoTime()
        Log.d(TAG, String.format(Locale.getDefault(), "Sending %s request [url = %s]", method, url))
        //the request body
        val requestBody = request.body
        if (requestBody != null) {
            val sb = StringBuilder("Request Body [")
            val buffer = Buffer()
            requestBody.writeTo(buffer)
            var charset = Charset.forName("UTF-8")
            val contentType = requestBody.contentType()
            if (contentType != null) {
                charset = contentType.charset(charset)
            }
            if (isPlaintext(buffer)) {
                sb.append(buffer.readString(charset!!))
                sb.append(" (Content-Type = ").append(contentType.toString()).append(",")
                    .append(requestBody.contentLength()).append("-byte body)")
            } else {
                sb.append(" (Content-Type = ").append(contentType.toString())
                    .append(",binary ").append(requestBody.contentLength())
                    .append("-byte body omitted)")
            }
            sb.append("]")
            Log.d(TAG, String.format(Locale.getDefault(), "%s %s", method, sb.toString()))
        }
        val response: Response = chain.proceed(request)
        val t2 = System.nanoTime()
        //the response time
        Log.d(
            TAG, String.format(
                Locale.getDefault(), "Received response for [url = %s] in %.1fms", url,
                (t2 - t1) / 1e6
            )
        )

        //the response state
        Log.d(
            TAG,
            String.format(
                Locale.CHINA,
                "Received response is %s ,message[%s],code[%d]",
                if (response.isSuccessful) "success" else "fail",
                response.message,
                response.code
            )
        )

        //the response data
        val body = response.body

        val source = body!!.source()
        source.request(Long.MAX_VALUE) // Buffer the entire body.
        val buffer = source.buffer
        var charset = Charset.defaultCharset()
        val contentType = body.contentType()
        if (contentType != null) {
            charset = contentType.charset(charset)
        }
        val bodyString = buffer.clone().readString(charset!!)
        Log.d(TAG, String.format("Received response json string [%s]", bodyString))

        return response
    }

    fun isPlaintext(buffer: Buffer): Boolean {
        try {
            val prefix = Buffer()
            val byteCount = if (buffer.size < 64) buffer.size else 64
            buffer.copyTo(prefix, 0, byteCount)
            for (i in 0..15) {
                if (prefix.exhausted()) {
                    break
                }
                val codePoint = prefix.readUtf8CodePoint()
                if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
                    return false
                }
            }
            return true
        } catch (e: EOFException) {
            return false // Truncated UTF-8 sequence.
        }
    }
}